/**
 * 胶囊按钮对齐工具
 * 用于动态计算胶囊按钮位置并应用到页面头部
 */

/**
 * 获取胶囊按钮对齐样式
 * @returns 包含对齐样式的对象
 */
export function getCapsuleAlignmentStyle(): Promise<{
  headerStyle: string;
  statusBarHeight: number;
  capsuleHeight: number;
  capsuleTop: number;
}> {
  return new Promise((resolve) => {
    try {
      // 获取胶囊按钮信息
      const capsuleInfo = wx.getMenuButtonBoundingClientRect();
      
      // 获取系统信息
      wx.getSystemInfo({
        success: (res) => {
          const statusBarHeight = res.statusBarHeight || 44;
          const capsuleTop = capsuleInfo.top - statusBarHeight;
          const capsuleHeight = capsuleInfo.height;
          
          // 计算页面头部样式 - 往上移动一个位置，根据胶囊高度显示在中间
          const headerStyle = `
            padding-top: ${statusBarHeight + capsuleTop - 8}px;
            height: ${capsuleHeight}px;
            display: flex;
            align-items: center;
            justify-content: center;
          `;
          
          resolve({
            headerStyle,
            statusBarHeight,
            capsuleHeight,
            capsuleTop
          });
        },
        fail: () => {
          // 失败时使用默认值
          resolve({
            headerStyle: 'padding-top: 42px; height: 32px; display: flex; align-items: center; justify-content: center;',
            statusBarHeight: 44,
            capsuleHeight: 32,
            capsuleTop: 6
          });
        }
      });
    } catch (error) {
      console.warn('获取胶囊按钮对齐样式失败:', error);
      // 使用默认值
      resolve({
        headerStyle: 'padding-top: 42px; height: 32px; display: flex; align-items: center; justify-content: center;',
        statusBarHeight: 44,
        capsuleHeight: 32,
        capsuleTop: 6
      });
    }
  });
}

/**
 * 在页面中初始化胶囊按钮对齐
 * @param pageInstance 页面实例
 */
export function initCapsuleAlignment(pageInstance: any): void {
  getCapsuleAlignmentStyle().then((alignment) => {
    pageInstance.setData({
      headerStyle: alignment.headerStyle
    });
    
    console.log('胶囊按钮对齐初始化完成:', alignment);
  });
}

/**
 * 获取默认的胶囊按钮对齐样式（静态）
 * @returns 默认样式字符串
 */
export function getDefaultCapsuleStyle(): string {
  return `
    padding-top: calc(env(safe-area-inset-top) - 2px);
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  `;
} 